package com.byit.ueditor.upload;

import com.byit.ueditor.PathFormat;
import com.byit.ueditor.define.AppInfo;
import com.byit.ueditor.define.BaseState;
import com.byit.ueditor.define.FileType;
import com.byit.ueditor.define.State;
import com.byit.utils.SpringUtil;
import io.minio.MinioClient;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 基于Minio的上传文件类
 */

public class MinioUploader {
	private static Logger log = LoggerFactory.getLogger(MinioUploader.class);

	public static final State save(HttpServletRequest request,
								   Map<String, Object> conf) {
        FileInputStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}



        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());


        String contentType = multipartFile.getContentType();




		try {
            fileStream = (FileInputStream) multipartFile.getInputStream();

			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			String physicalPath = (String) conf.get("rootPath") + savePath;


            // 获取Minio实例
            MinioClient minioClient = SpringUtil.getBean(MinioClient.class);

			String format = "/images/{yyyy}{mm}{dd}/{time}{rand:6}";
			String objectName = PathFormat.parse(format) + suffix;

			State storageState;

            String bucketName = "ueditor";

            try {
                minioClient.putObject(bucketName, objectName, fileStream, contentType);

                storageState = new BaseState(true);
                storageState.putInfo( "size", maxSize );
                storageState.putInfo( "title", originFileName );
                storageState.putInfo("url",   bucketName + objectName );
                storageState.putInfo("type", suffix);
                storageState.putInfo("original", originFileName + suffix);


            } catch (Exception e) {
                log.error("", e);
                return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
            }

            fileStream.close();

			return storageState;
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
